#include <iostream>

using namespace std;

#include "types.h"
#include "helper.h"
#include "rsakeys.h"
#include "base64.h"
#include "crypto.h"
#include "cmdargs.h"

cmdargs args;

void printUsage()
{
	cout  << "usage" << endl;
}



int main (int argc, char *argv[])
{
	int i;
	rsakeys mykeys;

	cout << "input command: ";
	for (i = 0; i < argc; i++)
		cout << argv[i] << " ";

	cout << endl;
	
	if (argc < 2)
	{ 
		printUsage();
		return -1;
	}

	args.rsacmd = argv[1];
	for (i = 2; i < argc; i++)
	{
		if (!strcmp(argv[i], "-out")) args.outfile = argv[++i];			
		else if (!strcmp(argv[i], "-in")) 			args.infile = argv[++i];
		else if (!strcmp(argv[i], "-inform")) 	args.inform = argv[++i];
		else if (!strcmp(argv[i], "-outform")) 	args.outform = argv[++i];
		else if (!strcmp(argv[i], "-keysize")) 	args.keysize = stringToInt(string(argv[++i]));
		else if (!strcmp(argv[i], "-pubout")) 	args.pubout = TRUE;
		else if (!strcmp(argv[i], "-inkey")) 		args.inkey = argv[++i];
		else if (!strcmp(argv[i], "-pubin"))		args.pubin = TRUE;
		else if (!strcmp(argv[i], "-encrypt"))	args.encrypt = TRUE;
		else if (!strcmp(argv[i], "-decrypt"))	args.decrypt = TRUE;
		else if (!strcmp(argv[i], "-cert"))			args.keyfromcert = TRUE;
		else if (!strcmp(argv[i], "-verify"))  	args .verify = TRUE;
		else if (!strcmp(argv[i], "-orig")) 		args.orig = argv[++i];
			else goto ERROR;
		
	}
	
	if (!args.rsacmd.compare("genrsa"))
	{
		if (FALSE == mykeys.createPrivKey())
			goto ERROR;
	}
	else if (!args.rsacmd.compare("rsa"))
	{
		if (args.pubout == TRUE)
		{
			if (!args.outfile.empty()) // save pub key to a file
				if (FALSE == mykeys.createPubKey())
					goto ERROR;
		}
		else if (!args.infile.empty())
		{
			if (!args.outfile.empty())
			{
				if (mykeys.convertPrivKeyFile() == FALSE)
				{
					cout << "error converting private key" << endl;
					goto ERROR;
				}
			}
		}
		else
			goto ERROR;
	}
	else if (!args.rsacmd.compare("rsautl"))
	{
		if (args.verify == TRUE)
		{	
			if (FALSE == rsaVerify())
				goto ERROR;
		}
		else if (args.encrypt == TRUE)
		{
			if (FALSE == rsaEncrypt())
				goto ERROR;
		}
		else if (args.decrypt == TRUE)
		{
			if (FALSE == rsaDecrypt())
				goto ERROR;
		}
		else
			goto ERROR;

	}
	else
		goto ERROR; 

	cout << endl;

	return 0;

	ERROR:
		printUsage();
		return -1;
}

